package com.luxondata.module.system.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.luxondata.module.system.entry.User;
import com.luxondata.module.system.repository.UserRepository;

@Component
public class UserService implements  UserDetailsService{
	
	@Autowired
	private UserRepository userRepository;
	

	/** spring标准加密 */
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 获取所有用户信息
	 * @return
	 */
    public List getAll() {  
    	return userRepository.findAll();  
    }

	public User findByUsername(String name) throws UsernameNotFoundException {
		User user = userRepository.findByUsername(name);
		return user;
	} 
	
	public User findByApiKey(String apiKey) throws UsernameNotFoundException {
		User user = userRepository.findByApiKey(apiKey);
		return user;
	} 
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserDetails userDetails = userRepository.findByUsername(username);
		if (userDetails == null) {
			throw new UsernameNotFoundException("Cannot find user with username " + username);
		}
		return userDetails;
	} 
	

	
	public User saveUser(User user)  {
		user.setCreateDate(new Date());
		user.setCreateUser((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal());
		entryptPassword(user);
		return userRepository.save(user);
	} 
	
	
	/**
	 * 使用spring标准的加密算法对明文密码进行加密
	 * 
	 * @param	user
	 * 			用户实体
	 */
	private void entryptPassword(User user) {
		passwordEncoder = new BCryptPasswordEncoder();
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			String encryptedPassword = passwordEncoder.encode(user.getPlainPassword());
			user.setPassword(encryptedPassword);
			user.setPlainPassword(null);
		}
	}
}
